import { getGameObjectById } from "../engine";
import { Behaviour } from "../engine/Behaviour";
import { number } from "../engine/validators/number";
import { RigidBody } from "./RigidBody";
import { AnimationRenderer } from "../engine/AnimationRenderer";
import { MainRolePrefabBinding } from "../bindings/MainRolePrefabBinding";

export class Walkable extends Behaviour {
  @number()
  walkspeed = 1;
  jumpspeed = 5;

  onStart() {

    window.addEventListener('keydown', (event) => {
      const role = getGameObjectById('mainRole');
      const rigid = role.getBehaviour(RigidBody);
      if (event.key === 'a' || event.key === 'A') {
        role.getBehaviour(MainRolePrefabBinding).action = 'moveleft'
        rigid.b2RigidBody.SetLinearVelocity({ x: -this.walkspeed, y: 0 });
        this.play(4);
      }
      if (event.key === 'd' || event.key === 'D') {
        role.getBehaviour(MainRolePrefabBinding).action = 'moveright'
        rigid.b2RigidBody.SetLinearVelocity({ x: this.walkspeed, y: 0 });
        this.play(4);
      }

    })

    window.addEventListener('keypress', (event) => {
      const role = getGameObjectById('mainRole');
      const rigid = role.getBehaviour(RigidBody);
      if (event.key === 'w' || event.key === 'W') {
        rigid.b2RigidBody.SetLinearVelocity({ x: 0, y: this.jumpspeed });
        this.play(3);
      }
    })

    window.addEventListener('keyup', (event) => {
      const role = getGameObjectById('mainRole');
      const rigid = role.getBehaviour(RigidBody);
      if (event.key === 'a' || event.key === 'A') {
        role.getBehaviour(MainRolePrefabBinding).action = 'idleleft';
        rigid.b2RigidBody.SetLinearVelocity({ x: 0, y: 0 });
      }
      if (event.key === 'd' || event.key === 'D') {
        role.getBehaviour(MainRolePrefabBinding).action = 'idleright';
        rigid.b2RigidBody.SetLinearVelocity({ x: 0, y: 0 });
      }
      if (event.key === 'w' || event.key === 'W') {
        rigid.b2RigidBody.SetLinearVelocity({ x: 0, y: 0 });
      }
    })
  }

  public play(flag) {
    let audio;
    switch (flag) {
      case 1:
        audio = new Audio("assets/music/death.wav");
        break;
      case 2:
        audio = new Audio("assets/music/down.wav");
      case 3:
        audio = new Audio("assets/music/jump.wav");
      case 4:
        audio = new Audio("assets/music/run.wav");
    }

    let AudioContext = new (window.AudioContext);
    let source = AudioContext.createMediaElementSource(audio)
    let analyser = AudioContext.createAnalyser();
    source.connect(analyser);
    analyser.connect(AudioContext.destination);
    audio.currentTime = 0;
    audio.play();
    // while (1) {
    //     audio.play();
    // }
  }
}
